<?php
namespace App\Http\Controllers\Admin;
use App\Models\XS\CmsXS;
use App\Models\XS\JobXS;
use App\Models\XS\ResumeXS;
use Illuminate\Http\Request;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Style;

//后台search讯搜的设置
class XunSearchController extends CommonController
{
    /**设置的界面
     * @return mixed
     */
    public function index()
    {
        return Style::view('admin.xunsearch.index');
    }

    /**设置的界面
     * @return mixed
     */
    public function insert_job(Request $request)
    {
        $jobxs = new JobXS();
        $result = $jobxs->storeAllJob($request);
        if($result['result'] == '2')
            $this->cleanOldLog(JobXS::$cms_job_path);
        $page = isset($request->page)?($request->page+1):2;
        $result['page'] = $page;
        return Style::view('admin.xunsearch.insert_job',$result);
    }

    /**设置的界面
     * @return mixed
     */
    public function insert_resume(Request $request)
    {
        $resumexs = new ResumeXS();
        $result = $resumexs->storeAllResume($request);
        if($result['result'] == '2')
            $this->cleanOldLog(ResumeXS::$cms_resume_path);
        $page = isset($request->page)?($request->page+1):2;
        $result['page'] = $page;
        return Style::view('admin.xunsearch.insert_resume',$result);
    }

    /**重建岗位或职位的讯搜的阴
     * @$storeAll 1为重建简历，2为重建职位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function rebuildXS($storeAll){
//        $input = $request->only('storeAll');
//        $storeAll = $input['storeAll'];
        if($storeAll == '1'){

            $resumexs = new ResumeXS();
            $result = $resumexs->storeAllResume();
            if($result)
                $this->cleanOldLog(ResumeXS::$cms_resume_path);
            return ['status'=>1, 'result'=>$result['result'], 'message'=>'简历更新成功！'];
        }elseif($storeAll == '2'){
            $jobxs = new JobXS();
            $result = $jobxs->storeAllJob();
            if($result)
                $this->cleanOldLog(JobXS::$cms_job_path);
            return ['status'=>1, 'result'=>$result['result'], 'message'=>'职位更新成功！'];
        }
    }

    /**读取日志文件，展示在讯搜的更新缓存页面
     * @param Request $request
     * @return string
     */
    public function readLog(Request $request)
    {
        $input = $request->only('storeAll');
        $storeAll = $input['storeAll'];
        if($storeAll == '1'){
            $dirName = ResumeXS::$cms_resume_path;
        }elseif($storeAll == '2'){
            $dirName = JobXS::$cms_job_path;
        }
        //读写文件
        $file_path = storage_path('logs/xs/'.$dirName.'/'.date('Y-m-d',time()).'.log');

        if (file_exists($file_path)) {
            $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
            $arr = explode("\n",$str);
            foreach ($arr as &$item) {
                $item = str_replace(' xunSearch.INFO','',$item);
                $item = str_replace(' []','',$item);
            }
            $str = implode("<br>",$arr);
            if(mb_substr($str,-9)=='<br> <br>'){
                return response()->json(['status'=>1,'message'=>'读取完成！','data'=>$str]);
            }else{
                return response()->json(['status'=>0,'message'=>'读取中！','data'=>$str]);
            }
        }
    }

    /**删除其他文件，仅剩最近的3个日志文件
     * @param $dirName
     */
    public function cleanOldLog($dirName)
    {
        $dir = storage_path('logs/xs/'.$dirName.'/');
        $fileNameArr = [];//所有日志文件的文件名
        if (is_dir($dir)) {
            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                    if(filetype($dir . $file)=='file'){
                        $fileExp = explode('.',$file);
                        $fileNameArr[] = $fileExp[0];
                    }
                } closedir($dh);
            }
        }
        if(count($fileNameArr) > 3){
            rsort($fileNameArr);
            foreach($fileNameArr as $key=>$value){
                if($key >2){
                    unlink(storage_path('logs/xs/'.$dirName.'/'.$value.'.log'));
                }
            }

        }
    }

    /** 改写迅搜ip
     * @param Request $request
     * @return string
     */
    public function resetIp(Request $request)
    {
        $file_path = 'xunsearch_resume.ini';

        if ($request->input('job', 1) == 1) $file_path = 'xunsearch_job.ini';

        $file_path = config_path($file_path);

        if (!file_exists($file_path))
            return ['status'=>0,'message'=>"文件 $file_path 不存在",'data'=>[]];

        if (!is_writable($file_path))
            return ['status'=>0,'message'=>"文件 $file_path 不可写",'data'=>[]];

        $ip = $request->input('ip','');

        if (!empty($ip)) {
            $ip .= ':';
        }

        $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中

        $arr = explode("\n",$str);

        $arr[2] = "server.index = $ip".'8383';
        $arr[3] = "server.search = $ip".'8384';

        $str1 = implode("\n",$arr);

        if (file_put_contents($file_path, $str1)) {
            return ['status'=>1,'message'=>"文件 $file_path 修改成功".$arr[2].$arr[3],'data'=>[]];
        }

        return ['status'=>0,'message'=>"文件 $file_path 修改失败",'data'=>[]];
    }
}